{% extends "layout.html" %}

{% block title %}音乐搜索{% endblock %}

{% block css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/music.css') }}">
<style>
    /* 默认图片的备用方案 */
    .default-cover-fallback {
        width: 100%;
        height: 100%;
        background-color: #4a90e2;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 3rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="music-container">
    <!-- 头部标题 -->
    <div class="music-header">
        <h1><i class="fas fa-music"></i> 免费音乐下载</h1>
    </div>
    
    <!-- 搜索框 -->
    <div class="search-container">
        <input type="text" id="searchInput" class="search-input" placeholder="搜索歌曲、歌手..." />
        <button id="searchButton" class="search-button">
            <i class="fas fa-search"></i> 搜索
        </button>
    </div>
    
    <!-- 播放器组件 -->
    <div id="playerContainer" class="player-container">
        <div class="player-left">
            <div class="music-cover">
                <div class="default-cover-fallback" id="defaultCoverFallback">
                    <i class="fas fa-music"></i>
                </div>
                <img id="musicCover" style="display:none;" src="" alt="音乐封面" onerror="handleCoverError()">
            </div>
        </div>
        <div class="player-right">
            <div class="music-info">
                <h2 id="musicTitle" class="music-title">未播放</h2>
                <p id="musicArtist" class="music-artist">未知歌手</p>
            </div>
            
            <div id="lyricsContainer" class="lyrics-container">
                <!-- 歌词将动态插入 -->
                <p class="lyrics-line">加载歌词中...</p>
            </div>
            
            <div class="controls-container">
                <div class="controls-left">
                    <button id="playPauseButton" class="play-button">
                        <i class="fas fa-play"></i>
                    </button>
                    <button id="nextButton" class="next-button">
                        <i class="fas fa-step-forward"></i>
                    </button>
                    
                    <span id="currentTime" class="audio-time">0:00</span>
                    <div id="progressContainer" class="audio-progress-container">
                        <div id="progressBar" class="audio-progress"></div>
                    </div>
                    <span id="totalTime" class="audio-time">0:00</span>
                </div>
                
                <div class="volume-container">
                    <i id="volumeIcon" class="fas fa-volume-up volume-icon"></i>
                    <div id="volumeContainer" class="volume-slider">
                        <div id="volumeBar" class="volume-progress"></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 实际的音频元素 -->
        <audio id="audioPlayer" style="display: none;"></audio>
    </div>
    
    <!-- 加载动画 -->
    <div id="loading" class="loading">
        <i class="fas fa-spinner"></i>
    </div>
    
    <!-- 搜索结果 -->
    <div id="searchResults" class="search-results" style="display: none;">
        <h3 class="results-title">搜索结果</h3>
        <table class="music-list">
            <thead>
                <tr>
                    <th>#</th>
                    <th>歌曲</th>
                    <th>歌手</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="musicListBody">
                <!-- 结果将动态插入 -->
            </tbody>
        </table>
        
        <!-- 分页控件 -->
        <div id="pagination" class="pagination">
            <!-- 分页按钮将动态插入 -->
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // DOM元素
        const searchInput = document.getElementById('searchInput');
        const searchButton = document.getElementById('searchButton');
        const playerContainer = document.getElementById('playerContainer');
        const musicCover = document.getElementById('musicCover');
        const defaultCoverFallback = document.getElementById('defaultCoverFallback');
        const musicTitle = document.getElementById('musicTitle');
        const musicArtist = document.getElementById('musicArtist');
        const lyricsContainer = document.getElementById('lyricsContainer');
        const playPauseButton = document.getElementById('playPauseButton');
        const nextButton = document.getElementById('nextButton');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const currentTime = document.getElementById('currentTime');
        const totalTime = document.getElementById('totalTime');
        const volumeIcon = document.getElementById('volumeIcon');
        const volumeContainer = document.getElementById('volumeContainer');
        const volumeBar = document.getElementById('volumeBar');
        const audioPlayer = document.getElementById('audioPlayer');
        const loading = document.getElementById('loading');
        const searchResults = document.getElementById('searchResults');
        const musicListBody = document.getElementById('musicListBody');
        const pagination = document.getElementById('pagination');
        
        // 处理封面图像加载错误
        window.handleCoverError = function() {
            musicCover.style.display = 'none';
            defaultCoverFallback.style.display = 'flex';
        };
        
        // 状态变量
        let currentPage = 1;
        let totalPages = 1;
        let searchKey = '';
        let musicList = [];
        let currentMusicIndex = -1;
        let lyrics = [];
        let lyricTimer = null;
        
        // 初始化音量
        audioPlayer.volume = 1.0;
        
        // 搜索函数
        function searchMusic(page = 1) {
            if (!searchKey.trim()) return;
            
            currentPage = page;
            loading.classList.add('active');
            searchResults.style.display = 'none';
            
            fetch(`/music/search?key=${encodeURIComponent(searchKey)}&pn=${page}`)
                .then(response => response.json())
                .then(data => {
                    musicList = data;
                    renderMusicList();
                    renderPagination();
                    
                    searchResults.style.display = 'block';
                    loading.classList.remove('active');
                })
                .catch(error => {
                    console.error('搜索出错:', error);
                    alert('搜索失败，请稍后重试');
                    loading.classList.remove('active');
                });
        }
        
        // 渲染音乐列表
        function renderMusicList() {
            musicListBody.innerHTML = '';
            
            if (musicList.length === 0) {
                musicListBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">未找到相关歌曲</td></tr>';
                return;
            }
            
            musicList.forEach((music, index) => {
                const row = document.createElement('tr');
                
                row.innerHTML = `
                    <td class="song-index">${index + 1}</td>
                    <td class="song-title">${music.name}</td>
                    <td class="song-artist">${music.artist}</td>
                    <td class="song-actions">
                        <button class="play-song" data-index="${index}">
                            <i class="fas fa-play"></i>
                        </button>
                        <button class="download-song" data-index="${index}">
                            <i class="fas fa-download"></i>
                        </button>
                    </td>
                `;
                
                musicListBody.appendChild(row);
                
                // 添加播放点击事件
                row.querySelector('.play-song').addEventListener('click', function() {
                    playMusic(index);
                });
                
                // 添加下载点击事件
                row.querySelector('.download-song').addEventListener('click', function() {
                    downloadMusic(index);
                });
            });
        }
        
        // 渲染分页控件
        function renderPagination() {
            pagination.innerHTML = '';
            
            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.innerHTML = '<i class="fas fa-chevron-left"></i> 上一页';
            prevButton.disabled = currentPage <= 1;
            prevButton.addEventListener('click', () => {
                searchMusic(currentPage - 1);
            });
            pagination.appendChild(prevButton);
            
            // 页码按钮
            const pageButton = document.createElement('button');
            pageButton.classList.add('current-page');
            pageButton.textContent = currentPage;
            pagination.appendChild(pageButton);
            
            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.innerHTML = '下一页 <i class="fas fa-chevron-right"></i>';
            nextButton.addEventListener('click', () => {
                searchMusic(currentPage + 1);
            });
            pagination.appendChild(nextButton);
        }
        
        // 播放音乐
        function playMusic(index) {
            if (index < 0 || index >= musicList.length) return;
            
            currentMusicIndex = index;
            const music = musicList[index];
            
            // 显示加载动画
            loading.classList.add('active');
            playerContainer.classList.remove('active');
            
            // 重置播放器状态
            audioPlayer.pause();
            audioPlayer.currentTime = 0;
            progressBar.style.width = '0%';
            playPauseButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            
            // 获取MP3链接
            fetch(`/music/mp3?rid=${music.rid}`)
                .then(response => response.text())
                .then(mp3Url => {
                    // 设置音频源
                    audioPlayer.src = mp3Url;
                    audioPlayer.load();
                    
                    // 更新UI
                    musicTitle.textContent = music.name;
                    musicArtist.textContent = music.artist;
                    
                    // 设置封面
                    if (music.pic) {
                        musicCover.src = music.pic;
                        musicCover.style.display = 'block';
                        defaultCoverFallback.style.display = 'none';
                    } else {
                        musicCover.style.display = 'none';
                        defaultCoverFallback.style.display = 'flex';
                    }
                    
                    // 播放音乐
                    audioPlayer.play().then(() => {
                        playPauseButton.innerHTML = '<i class="fas fa-pause"></i>';
                    }).catch(error => {
                        console.error('播放失败:', error);
                        playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
                    });
                    
                    // 获取歌词
                    loadLyrics(music.rid);
                    
                    // 显示播放器
                    playerContainer.classList.add('active');
                    loading.classList.remove('active');
                })
                .catch(error => {
                    console.error('获取MP3链接失败:', error);
                    alert('获取音乐失败，请稍后重试');
                    loading.classList.remove('active');
                    playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
                });
        }
        
        // 加载歌词
        function loadLyrics(rid) {
            // 清除之前的歌词
            clearInterval(lyricTimer);
            lyricsContainer.innerHTML = '<p class="lyrics-line">加载歌词中...</p>';
            
            fetch(`/music/lyric?rid=${rid}`)
                .then(response => response.json())
                .then(data => {
                    lyrics = data;
                    
                    if (lyrics.length === 0) {
                        lyricsContainer.innerHTML = '<p class="lyrics-line">暂无歌词</p>';
                        return;
                    }
                    
                    renderLyrics();
                    
                    // 设置歌词滚动定时器
                    lyricTimer = setInterval(updateActiveLyric, 300);
                })
                .catch(error => {
                    console.error('获取歌词失败:', error);
                    lyricsContainer.innerHTML = '<p class="lyrics-line">获取歌词失败</p>';
                });
        }
        
        // 渲染歌词
        function renderLyrics() {
            lyricsContainer.innerHTML = '';
            
            lyrics.forEach((line, index) => {
                const lyricElement = document.createElement('p');
                lyricElement.className = 'lyrics-line';
                lyricElement.textContent = line.lineLyric;
                lyricElement.dataset.time = line.time;
                lyricElement.dataset.index = index;
                
                lyricsContainer.appendChild(lyricElement);
            });
        }
        
        // 更新当前歌词
        function updateActiveLyric() {
            if (!audioPlayer.duration || lyrics.length === 0) return;
            
            const currentLyricElements = lyricsContainer.querySelectorAll('.lyrics-line');
            let activeIndex = -1;
            
            // 查找当前歌词
            for (let i = lyrics.length - 1; i >= 0; i--) {
                if (parseFloat(lyrics[i].time) <= audioPlayer.currentTime) {
                    activeIndex = i;
                    break;
                }
            }
            
            // 更新高亮状态
            currentLyricElements.forEach((el, index) => {
                if (index === activeIndex) {
                    el.classList.add('active');
                    
                    // 滚动到当前歌词
                    const containerHeight = lyricsContainer.clientHeight;
                    const lyricHeight = el.clientHeight;
                    const scrollTop = el.offsetTop - containerHeight / 2 + lyricHeight / 2;
                    
                    lyricsContainer.scrollTo({
                        top: scrollTop,
                        behavior: 'smooth'
                    });
                } else {
                    el.classList.remove('active');
                }
            });
        }
        
        // 格式化时间
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
        }
        
        // 下载音乐
        function downloadMusic(index) {
            if (index < 0 || index >= musicList.length) return;
            
            const music = musicList[index];
            
            fetch(`/music/mp3?rid=${music.rid}`)
                .then(response => response.text())
                .then(mp3Url => {
                    const link = document.createElement('a');
                    link.href = mp3Url;
                    link.download = `${music.name} - ${music.artist}.mp3`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                })
                .catch(error => {
                    console.error('下载失败:', error);
                    alert('下载失败，请稍后重试');
                });
        }
        
        // 播放下一首
        function playNextMusic() {
            if (currentMusicIndex >= 0 && currentMusicIndex < musicList.length - 1) {
                playMusic(currentMusicIndex + 1);
            }
        }
        
        // 事件监听器
        
        // 搜索按钮点击事件
        searchButton.addEventListener('click', function() {
            searchKey = searchInput.value.trim();
            if (searchKey) {
                searchMusic(1);
            }
        });
        
        // 回车键搜索
        searchInput.addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                searchKey = searchInput.value.trim();
                if (searchKey) {
                    searchMusic(1);
                }
            }
        });
        
        // 播放/暂停按钮点击事件
        playPauseButton.addEventListener('click', function() {
            if (audioPlayer.paused) {
                audioPlayer.play();
                playPauseButton.innerHTML = '<i class="fas fa-pause"></i>';
            } else {
                audioPlayer.pause();
                playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
            }
        });
        
        // 下一首按钮点击事件
        nextButton.addEventListener('click', playNextMusic);
        
        // 进度条点击事件
        progressContainer.addEventListener('click', function(event) {
            if (!audioPlayer.duration) return;
            
            const percent = (event.offsetX / progressContainer.clientWidth);
            audioPlayer.currentTime = percent * audioPlayer.duration;
            progressBar.style.width = `${percent * 100}%`;
        });
        
        // 音量图标点击事件
        volumeIcon.addEventListener('click', function() {
            if (audioPlayer.volume > 0) {
                audioPlayer.volume = 0;
                volumeIcon.className = 'fas fa-volume-mute volume-icon';
                volumeBar.style.width = '0%';
            } else {
                audioPlayer.volume = 1;
                volumeIcon.className = 'fas fa-volume-up volume-icon';
                volumeBar.style.width = '100%';
            }
        });
        
        // 音量控制点击事件
        volumeContainer.addEventListener('click', function(event) {
            const percent = (event.offsetX / volumeContainer.clientWidth);
            audioPlayer.volume = percent;
            volumeBar.style.width = `${percent * 100}%`;
            
            // 更新音量图标
            if (percent === 0) {
                volumeIcon.className = 'fas fa-volume-mute volume-icon';
            } else if (percent < 0.5) {
                volumeIcon.className = 'fas fa-volume-down volume-icon';
            } else {
                volumeIcon.className = 'fas fa-volume-up volume-icon';
            }
        });
        
        // 音频事件
        audioPlayer.addEventListener('timeupdate', function() {
            if (!audioPlayer.duration) return;
            
            const percent = (audioPlayer.currentTime / audioPlayer.duration) * 100;
            progressBar.style.width = `${percent}%`;
            currentTime.textContent = formatTime(audioPlayer.currentTime);
        });
        
        audioPlayer.addEventListener('loadedmetadata', function() {
            totalTime.textContent = formatTime(audioPlayer.duration);
        });
        
        audioPlayer.addEventListener('ended', function() {
            playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
            
            // 自动播放下一首
            playNextMusic();
        });
        
        // 初始检查url参数是否有搜索关键词
        const urlParams = new URLSearchParams(window.location.search);
        const urlKey = urlParams.get('key');
        if (urlKey) {
            searchInput.value = urlKey;
            searchKey = urlKey;
            searchMusic(1);
        }
    });
</script>
{% endblock %} 